package com.ikun.hosuserservice.config;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ikun.common.entity.ResponseResult;
import org.springframework.security.core.userdetails.User;
import com.ikun.common.utils.JwtUtils;
import com.ikun.common.utils.RsaUtils;
import com.ikun.hosuserservice.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功处理器
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //获得登录成功的用户信息
        User user = (User) authentication.getPrincipal();
        //通过手机号查询出用户信息
        com.ikun.common.entity.User user1 = userService.getOne(new QueryWrapper<com.ikun.common.entity.User>().lambda().eq(com.ikun.common.entity.User:: getPhone, user.getUsername()));
        //生成jwt字符串
        String token = JwtUtils.generateUserToken(user1, RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES);
        log.info("生成用户token：{}",token);
        //发送到前端
        ResponseResult.write(httpServletResponse,ResponseResult.ok(user1,token,""));
    }
}
